package com.cj.media.mediacodec

import android.Manifest
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.media.MediaPlayer
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.IBinder
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.cj.media.listener.ScreenCaptureListener
import com.cj.media.service.ScreenShortRecordService
import java.io.File

class MainActivity : AppCompatActivity() {

    private var mMediaProjectionManager : MediaProjectionManager? = null
    private var mMediaProjection : MediaProjection? = null

    //截屏、录屏服务
    private var mScreenShortService: ScreenShortRecordService? = null

    //截屏
    private val CAPTURE_CODE = 0x10
    //录屏
    private val MIRROR_CODE = 0x20

    private var ivImage:ImageView? = null

    //用于屏幕录制
    private var isRecord = false

    //保存媒体的文件夹路径
    private var path = ""
    private var fileName = "media_projection.mp4"

    private var btnRecord:Button? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        ivImage = findViewById(R.id.image)
        btnRecord = findViewById(R.id.btn_recorder)
        path = getExternalFilesDir(Environment.DIRECTORY_MOVIES)?.absolutePath + File.separator + "media_projection"
        checkPermission()
    }

    fun checkPermission(): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(
                Manifest.permission.CAMERA
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            requestPermissions(
                arrayOf(
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA
                ), 0x1234
            )
        }
        return false
    }

    fun start(view: View){
        mMediaProjectionManager = getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        //请求用户同意录屏
        val captureIntent = mMediaProjectionManager!!.createScreenCaptureIntent()
        startActivityForResult(captureIntent,0x01)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode == 0x01 && resultCode == RESULT_OK && data != null){
            mMediaProjection = mMediaProjectionManager?.getMediaProjection(resultCode,data)
            val encoder = ScreenCaptureEncoder(mMediaProjection!!,1080,1920)
            Thread({
                encoder.encode()
            }).start()
        }else if(requestCode == CAPTURE_CODE && resultCode == RESULT_OK && data != null){
            mScreenShortService?.startCapture(data, object : ScreenCaptureListener {

                override fun onSuccess(bitmap: Bitmap) {
                    //显示截图
                    showScreenCapture(bitmap)
                }

                override fun onFailure(e: Throwable) {
                    e.printStackTrace()
                }
            })
        }else if(requestCode == MIRROR_CODE && resultCode == RESULT_OK && data != null){
            //开始录制
            data?.let {
                mScreenShortService?.startRecorder(path, fileName, it)
            }
        }
    }

    private fun showScreenCapture(bitmap: Bitmap) {
        runOnUiThread({
            ivImage?.setImageBitmap(bitmap)
        })
    }

    fun startLive(view: View) {
        val intent = Intent(this,CameraCollectActivity::class.java)
        startActivity(intent)
    }

    private val connection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, iBinder: IBinder?) {
            if (iBinder is ScreenShortRecordService.ScreenShortBinder) {
                //截屏
                mScreenShortService = iBinder.getService()

            }
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            //no-op
        }
    }

    fun startCapture(view: View) {
        mScreenShortService?.let {
            //开始截屏
            mMediaProjectionManager =
                getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
            mMediaProjectionManager!!.createScreenCaptureIntent().apply {
                startActivityForResult(this, CAPTURE_CODE)
            }
        }
    }

    override fun onStart() {
        super.onStart()
        // 绑定服务
        Intent(this, ScreenShortRecordService::class.java)
            .also { intent ->
                bindService(intent, connection, Context.BIND_AUTO_CREATE)
            }
    }

    override fun onStop() {
        super.onStop()
        //解绑服务
        unbindService(connection)
    }

    fun startRecorder(view: View) {
        if(checkRecorderPermission()){
            startRecordScreen()
        }
    }

    fun startRecordScreen() {
        if(!isRecord){
            isRecord = true
            mMediaProjectionManager = getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
            mMediaProjectionManager!!.createScreenCaptureIntent().apply {
                startActivityForResult(this, MIRROR_CODE)
            }
            btnRecord?.text = "结束屏幕录制"
        }else{
            try {
                isRecord = false
                btnRecord?.text = "开始屏幕录制"
                //停止录制
                mScreenShortService?.stopRecorder()

            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    //权限检查和申请
    fun checkRecorderPermission(): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val checkSelfPermission = ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.RECORD_AUDIO
            )
            if (checkSelfPermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.RECORD_AUDIO),
                    200
                );
                return false
            }
        }
        return true
    }
}